// <copyright file="ProductRepository.cs" company="EnterpriseApi">
// Copyright (c) EnterpriseApi. All rights reserved.
// </copyright>

using EnterpriseApi.Data;
using EnterpriseApi.Models;
using Microsoft.EntityFrameworkCore;

namespace EnterpriseApi.Repositories;

/// <summary>
/// 产品仓储实现类，提供产品特有的数据访问操作
/// </summary>
public class ProductRepository : Repository<Product>, IProductRepository
{
    private readonly AppDbContext _context;

    /// <summary>
    /// 初始化ProductRepository的新实例
    /// </summary>
    /// <param name="context">数据库上下文</param>
    public ProductRepository(AppDbContext context) : base(context)
    {
        _context = context;
    }

    /// <summary>
    /// 根据类别获取产品列表
    /// </summary>
    /// <param name="categoryId">类别ID</param>
    /// <returns>特定类别的产品集合</returns>
    public async Task<IEnumerable<Product>> GetProductsByCategoryAsync(int categoryId)
    {
        return await _context.Products.Where(p => p.CategoryId == categoryId).ToListAsync();
    }

    /// <summary>
    /// 获取可用产品列表
    /// </summary>
    /// <returns>可用产品集合</returns>
    public async Task<IEnumerable<Product>> GetAvailableProductsAsync()
    {
        return await _context.Products.Where(p => p.IsAvailable && p.StockQuantity > 0).ToListAsync();
    }

    /// <summary>
    /// 根据价格范围获取产品
    /// </summary>
    /// <param name="minPrice">最低价格</param>
    /// <param name="maxPrice">最高价格</param>
    /// <returns>价格范围内的产品集合</returns>
    public async Task<IEnumerable<Product>> GetProductsByPriceRangeAsync(decimal minPrice, decimal maxPrice)
    {
        return await _context.Products
            .Where(p => p.Price >= minPrice && p.Price <= maxPrice)
            .ToListAsync();
    }

    /// <summary>
    /// 搜索产品（按名称或描述）
    /// </summary>
    /// <param name="searchTerm">搜索关键词</param>
    /// <returns>符合搜索条件的产品集合</returns>
    public async Task<IEnumerable<Product>> SearchProductsAsync(string searchTerm)
    {
        if (string.IsNullOrWhiteSpace(searchTerm))
        {
            return await GetAllAsync();
        }

        return await _context.Products
            .Where(p => p.Name.Contains(searchTerm) || (p.Description != null && p.Description.Contains(searchTerm)))
            .ToListAsync();
    }

    /// <summary>
    /// 检查产品库存是否足够
    /// </summary>
    /// <param name="productId">产品ID</param>
    /// <param name="quantity">所需数量</param>
    /// <returns>库存是否足够</returns>
    public async Task<bool> CheckStockAvailabilityAsync(int productId, int quantity)
    {
        var product = await _context.Products.FindAsync(productId);
        return product != null && product.IsAvailable && product.StockQuantity >= quantity;
    }
}